﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

namespace 视频流媒体管理
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        public static string token = "";
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btn登录_Click(object sender, EventArgs e)
        {
            string pwd = Code.摄像机管理.ONE.生成MD5(this.txt口令.Text.Trim().ToLower()); //口令用md5加密，小写
            string url = this.txthost.Text + "login";            //https://blog.csdn.net/qq_51860400/article/details/132455026

            Dictionary<string, string> dict = new Dictionary<string, string>();
            dict["username"] = this.txt用户id.Text.Trim();
            dict["password"] = pwd;
            dict["onlytoken"] = "true";

            视频流媒体管理.Code.HttpPost p = new Code.HttpPost();
            string cons = p.组合FormData(dict, out string contType);
            string str = p.PostData(url,  contType, cons, new Dictionary<string, string>());
            //{"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3MzAyNjcyMDksInB3IjoiMjEyMzJmMjk3YTU3YTVhNzQzODk0YTBlNGE4MDFmYzMiLCJ0bSI6MTczMDE4MDgwOSwidW4iOiJhZG1pbiJ9.a0ok1e7ohUbd5_2mdDOrsYJ3owelMxA4MKVfZOye_Bg"}
            //Newtonsoft.Json.Bson.j
            if (str.Contains("token") == false)
            {
                this.txtInfo.Text = "登录失败：" + str;
                token = "";
            }
            else
            {
                this.txtInfo.Text = "登录成功：" + str;
                JObject ob = JObject.Parse(str);
                token = ob["token"].ToString();
            }
        }

        protected void btn退出登录_Click(object sender, EventArgs e)
        {
            string url = this.txthost.Text + "logout?token=" + token;            //https://blog.csdn.net/qq_51860400/article/details/132455026

            WebClient cli = new WebClient();
            string str= cli.DownloadString(url); 
            this.txtInfo.Text = "退出信息：" + str;
        }

        protected void btn取得直播列表_Click(object sender, EventArgs e)
        {
            string url = this.txthost.Text + "live/list";
            url += "?token=" + token;
            url += "&start=0&limit=9999"; //三个参数

            视频流媒体管理.Code.HttpPost p = new Code.HttpPost();

            string str = p.GetData(url, "text/html", new Dictionary<string, string>());
            this.txtInfo.Text = "登录成功：" + str;
            JObject ob = JObject.Parse(str);
            JArray ja = ob["rows"] as JArray;
            DataTable dt = new DataTable();
            dt.Columns.Add("序号", typeof(int));
            dt.Columns.Add("id");
            dt.Columns.Add("name");
            dt.Columns.Add("直播开头"); //是否正在直播
            dt.Columns.Add("直播状态"); //是否正在直播
            dt.Columns.Add("src"); //源地址
            dt.Columns.Add("观众数量", typeof(int)); //观众人数
            dt.Columns.Add("hls"); //播放地址
            dt.Columns.Add("HTTP_FLV"); //播放地址

            int 序号 = 1;
            foreach (JToken j in ja)
            {
                JObject t = j["live"] as JObject;
                DataRow dr = dt.NewRow();
                dr["序号"] = 序号++;
                dr["id"] = t["id"];
                dr["name"] = t["name"];
                dr["直播开头"] = t["actived"];
                dr["src"] = t["source"];
                dr["直播状态"] = t["liveType"];

                JObject s = t["session"] as JObject;
                if (s != null)
                {
                    dr["hls"] = s["HLS"];
                    dr["HTTP_FLV"] = s["HTTP-FLV"];
                    dr["观众数量"] = s["NumOutputs"]; //播放hls时不算观众数量，不知为何
                }
                dt.Rows.Add(dr);
            }
            this.GridView1.DataSource = dt;
            this.GridView1.DataBind();
        }

        protected void btn取得直播列表0_Click(object sender, EventArgs e)
        {
            string url = this.txthost.Text + "live/get";
            url += "?token=" + token;
            url += "&id="+this.txt直接ID.Text; //每次只查一个

            视频流媒体管理.Code.HttpPost p = new Code.HttpPost();

            string str = p.GetData(url, "text/html", new Dictionary<string, string>());
            this.txtInfo.Text = "登录成功：" + str;
            if (str == "{}")
                return; //没有匹配
            JObject t = JObject.Parse(str);
            //JArray ja = JArray.Parse(str);
            DataTable dt = new DataTable();
            dt.Columns.Add("序号", typeof(int));
            dt.Columns.Add("id");
            dt.Columns.Add("name");
            dt.Columns.Add("直播开头"); //是否正在直播
            dt.Columns.Add("直播状态"); //是否正在直播
            dt.Columns.Add("src"); //源地址
            dt.Columns.Add("观众数量", typeof(int)); //观众人数
            dt.Columns.Add("HLS"); //播放地址
            dt.Columns.Add("HTTP_FLV"); //播放地址

            int 序号 = 1;
           // foreach (JToken t in ja)
            {
                //JObject t = j["live"] as JObject;
                DataRow dr = dt.NewRow();
                dr["序号"] = 序号++;
                dr["id"] = t["id"];
                dr["name"] = t["name"];
                dr["直播开头"] = t["actived"];
                dr["src"] = t["source"];
                dr["直播状态"] = t["liveType"];

                JObject s = t["session"] as JObject;
                if (s != null)
                {
                    dr["hls"] = s["HLS"];
                    dr["HTTP_FLV"] = s["HTTP-FLV"];
                    dr["观众数量"] = s["NumOutputs"];
                }
                dt.Rows.Add(dr);
            }
            this.GridView1.DataSource = dt;
            this.GridView1.DataBind();
        }

        protected void btn打开关闭直播_Click(object sender, EventArgs e)
        {
            string url = this.txthost.Text + "live/turn/actived";

            Dictionary<string, string> dict = new Dictionary<string, string>();
            dict["token"] = token;
            dict["id"] = this.txt直接ID.Text;
            dict["actived"] = this.txt直播开头.Text;

            视频流媒体管理.Code.HttpPost p = new Code.HttpPost();
            string cons = p.组合FormData(dict, out string contType);
            string str = p.PostData(url, contType, cons, new Dictionary<string, string>());
            //{"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3MzAyNjcyMDksInB3IjoiMjEyMzJmMjk3YTU3YTVhNzQzODk0YTBlNGE4MDFmYzMiLCJ0bSI6MTczMDE4MDgwOSwidW4iOiJhZG1pbiJ9.a0ok1e7ohUbd5_2mdDOrsYJ3owelMxA4MKVfZOye_Bg"}
            //Newtonsoft.Json.Bson.j
          
            this.txtInfo.Text = "打开关闭：：" + str; //{"code":200,"msg":"Success"}

        }

        protected void btn新增直播_Click(object sender, EventArgs e)
        {
            string url = this.txthost.Text + "live/save";

            Dictionary<string, string> dict = new Dictionary<string, string>();
            dict["token"] = token;
            dict["cid"] = this.txt摄像机ID.Text;
            dict["name"] = this.txt摄像机名.Text;
            dict["vo[type]"] = "online";
            dict["vo[src]"] = this.txt直接源.Text;
            dict["kind"] = "pull";
            dict["actived"] = "true"; //添加后开始直播，也可后续再控制

            视频流媒体管理.Code.HttpPost p = new Code.HttpPost();
            string cons = p.组合FormData(dict, out string contType);
            string str = p.PostData(url, contType, cons, new Dictionary<string, string>());
            //{"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3MzAyNjcyMDksInB3IjoiMjEyMzJmMjk3YTU3YTVhNzQzODk0YTBlNGE4MDFmYzMiLCJ0bSI6MTczMDE4MDgwOSwidW4iOiJhZG1pbiJ9.a0ok1e7ohUbd5_2mdDOrsYJ3owelMxA4MKVfZOye_Bg"}
            //Newtonsoft.Json.Bson.j

            this.txtInfo.Text = "新增直播：" + str; //{"code":200,"msg":"Success"}

    
        }

        protected void btn删除直播_Click(object sender, EventArgs e)
        {
            string url = this.txthost.Text + "live/remove";
            url += "?token=" + token;
            url += "&id=" + this.txt摄像机ID.Text; //每次只查一个

            视频流媒体管理.    Code.HttpPost p = new Code.HttpPost();

            string str = p.GetData(url, "text/html", new Dictionary<string, string>());
            this.txtInfo.Text = "删除信息：" + str;

        }

        /// <summary>
        /// 上传文件接口
        /// </summary>
        /// <param name="dictParam">上传参数</param>
        /// <param name="fileUrl">文件的地址</param>
        /// <param name="url">请求接口地址</param>
        /// <param name="encoding">字符编码格式</param>
        /// <param name="keyName">文件参数的参数名称</param>
        /// <returns></returns>
        //public static string UploadRequest(Dictionary<string, object> dictParam, string fileUrl, Encoding encoding, string url, string keyName)
        //{

        //    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        //    WebHeaderCollection header = request.Headers;
        //    request.Method = "post";

        //    //读取文件信息
        //    FileStream fileStream = new FileStream(fileUrl, FileMode.Open, FileAccess.Read, FileShare.Read);
        //    byte[] bytes = new byte[fileStream.Length];
        //    fileStream.Read(bytes, 0, bytes.Length);
        //    fileStream.Close();
        //    byte[] UpdateFile = bytes;//转换为二进制
        //    if (UpdateFile.Length == 0)
        //    {
        //        return "上传文件无效";
        //    }
        //    string Boundary = "--WebKitFormBoundary39B5a5e2FWoGbphs";
        //    //构造POST请求体
        //    StringBuilder PostContent = new StringBuilder("");

        //    //获取文件名称
        //    string filename = "";
        //    filename = Path.GetFileName(fileUrl);

        //    //组成普通参数信息
        //    foreach (KeyValuePair<string, object> item in dictParam)
        //    {
        //        PostContent.Append("--" + Boundary + "\r\n")
        //                   .Append("Content-Disposition: form-data; name=\"" + item.Key + "\"" + "\r\n\r\n" + (string)item.Value + "\r\n");
        //    }
        //    byte[] PostContentByte = encoding.GetBytes(PostContent.ToString());

        //    //处理文件参数信息
        //    StringBuilder FileContent = new StringBuilder();
        //    FileContent.Append("--" + Boundary + "\r\n")
        //            .Append("Content-Disposition:form-data; name=\"" + keyName + "\";filename=\"" + filename + "\"" + "\r\n\r\n");
        //    byte[] FileContentByte = encoding.GetBytes(FileContent.ToString());
        //    request.ContentType = "multipart/form-data;boundary=" + Boundary;
        //    byte[] ContentEnd = encoding.GetBytes("\r\n--" + Boundary + "--\r\n");//请求体末尾，后面会用到
        //                                                                          //定义请求流
        //    Stream myRequestStream = request.GetRequestStream();
        //    myRequestStream.Write(PostContentByte, 0, PostContentByte.Length);//写入参数
        //    myRequestStream.Write(FileContentByte, 0, FileContentByte.Length);//写入文件信息
        //    myRequestStream.Write(UpdateFile, 0, UpdateFile.Length);//文件写入请求流中
        //    myRequestStream.Write(ContentEnd, 0, ContentEnd.Length);//写入结尾   
        //    myRequestStream.Close();
        //    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        //    string encodingth = response.ContentEncoding;
        //    if (encodingth == null || encodingth.Length < 1)
        //    {
        //        encodingth = "GBK"; //默认编码,根据需求自己指定 
        //    }
        //    StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encodingth));
        //    string retString = reader.ReadToEnd();
        //    return retString;
        //}
    }
}